<template>
  <el-dialog v-model="dialog.visible" title="打招呼" width="45%" @close="handleCloseDialog">
    <div v-if="receiveInfo?.receiveCoupon == true" class="title">
      该业主在商城中领取了您的{{ receiveInfo?.ategoryName }}类券，支付查询费用{{
        receiveInfo?.points
      }}积分可看到业主的联系电话
    </div>

    <div class="form-container">
      <el-alert
        title="业主回复前仅可发送一次，可发送默认语句或自编辑内容，请确认"
        type="warning"
        :closable="false"
      />
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="150px" class="mt-5">
        <el-form-item label="" prop="radio">
          <el-radio-group v-model="formData.radio" @change="handleChangeGreet">
            <el-radio :value="1" class="!block">
              默认语(您好!专业装修方案，在线解答装修问题!)
            </el-radio>
            <el-radio :value="2" class="!block">自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="" prop="customWords">
          <el-input
            v-if="formData.radio === 2"
            v-model="formData.customWords"
            :autosize="{ minRows: 4, maxRows: 8 }"
            type="textarea"
            maxlength="150"
            placeholder="请输入打招呼语"
          />
        </el-form-item>
      </el-form>
    </div>
    <template v-if="canEdit" #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import OpportunityAPI from "@/api/opportunity";
import { useUserStore } from "@/store";
const userInfo = useUserStore().userInfo;

// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData"]);
const dialog = reactive({
  title: "",
  visible: false,
});
/*基础信息*/
const formRef = ref();
const radio = ref(1);

const defaultFormData = {
  radio: 1,
  greetWords: "",
  customWords: "",
};
const formData = ref({
  consumerId: undefined,
  houseId: undefined,
  paymentUserId: null,
  requirementId: 0,
  requirementType: undefined,
  categoryId: undefined,
  ...defaultFormData,
});
const receiveInfo = ref();
const formRules = reactive({
  customWords: [
    {
      validator: (rule, value, callback) => {
        if (!formData.value.customWords && formData.value.radio === 2) {
          callback(new Error("打招呼语不能为空"));
        } else if (formData.value.customWords.length > 150 && formData.value.radio === 2) {
          callback(new Error("打招呼语长度不能超过150个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

async function handleSubmit() {
  console.log(formData.value.radio);

  const validate = await formRef.value.validate();
  if (!validate) return;

  // 根据用户类型获取机会类型
  // 如果没被定义
  try {
    (formData.value.greetWords =
      formData.value.radio === 1 ? formData.value.greetWords : formData.value.customWords),
      await OpportunityAPI.sayHello(formData.value);
    ElMessage.success("成功");
    emit("loadData");
    handleCloseDialog();
  } catch (err) {}
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  Object.assign(formData.value, defaultFormData);
  emit("update:modelValue", false); // 关闭弹窗
}

async function handleChangeGreet() {
  await formRef.value.validate();
}

async function getInfos(data) {
  const res = await OpportunityAPI.getCheckReceiveCoupon(data);
  receiveInfo.value = res.data;
  console.log(res);
}
const canEdit = ref(true);
function showModal(val: any) {
  dialog.visible = true;
  const { greetWords, id } = val;
  formData.value.greetWords = greetWords || "您好!专业装修方案，在线解答装修问题!";
  formData.value.consumerId = val.userId;
  formData.value.houseId = val.houseId;
  formData.value.paymentUserId = userInfo.userId;
  formData.value.requirementId = val.id;
  formData.value.requirementType = val.type;
  formData.value.categoryId = val.categoryTypeId;
  const datas = {
    houseId: val.houseId,
    userId: userInfo.userId,
    categoryTypeId: val.categoryTypeId,
  };
  // getInfos(datas);
}

defineExpose({
  showModal,
});
</script>
<style style="scss" scoped>
.title {
  padding: 10px 0;
  font-size: 16px;
}
.form-container {
  height: 600px;
  overflow: auto;
}
::v-deep(.el-radio-group) {
  display: block;
}
</style>
